<template>
  <a-modal
    :open="modalModel.open"
    :title="modalModel.title"
    :width="400"
    @ok="handleOk"
    @cancel="close"
  >
    <a-form :model="form" @keyup.enter="handleOk" :rules="form.rules" :label-col="{span:6}" ref="formRef">
      <a-row>
        <a-col :span="24">
          <a-form-item label="用户账号" name="username">
            <a-input
              placeholder="请输入用户账号"
              v-model:value="form.username"
              :disabled="!isAdd"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="用户名称" name="realName">
            <a-input
              placeholder="请输入用户名称"
              v-model:value="form.realName"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="isAdd">
          <a-form-item label="密码" name="password">
            <a-input
              placeholder="请输入密码"
              v-model:value="form.password"
              type="password"
            />
          </a-form-item>
        </a-col>
      </a-row>


    </a-form>

  </a-modal>
</template>

<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { userUrl } from '@/api/api'
import { postAction } from '@/request/request'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'


const isAdd = ref(false)

let url = ''

watch(isAdd, (newVal, oldVal) => {
  modalModel.title = newVal ? '添加用户' : '修改用户'
  url = newVal ? userUrl.add : userUrl.edit
})

const modalModel = reactive({
  open: false,
  title: ''
})

const show = () => {
  modalModel.open = true
}
const formRef = ref(null)
const close = () => {
  modalModel.open = false
  formRef.value.resetFields()
}

const form = reactive({
  username: '',
  realName: '',
  password: '',
  rules:{
    username: [{ required: true, message: '请输入用户账号', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入用户密码', trigger: 'blur' }]
  }
})
const user = computed(() => {
  return useUserStore().user
})
const handleOk = () => {
  const data = {
    username: form.username,
    realName: form.realName,
    adminId:isAdd ? user.value.id:'',
    password: isAdd ? form.password:''
  }
  postAction(url, data).then(res => {
    if (res.code === 200) {
      ElMessage.success('操作成功')
      close()
    } else {
      ElMessage.error(res.message)
    }
  })
}

defineExpose({
  show,
  close,
  form,
  isAdd
})
</script>


<style scoped>

</style>